/*
 * Created on 05.05.2008
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package at.fhv.dcs.aw.j2me.net.socket;

import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;


public class BasicSocketMIDlet extends MIDlet {

    private String m_connectionDetails = "socket://localhost:4711";

    private class Reader implements Runnable {

        private StreamConnection m_connection;
        private DataInputStream m_dataInputStream;

        public void run() {
            try {
                m_connection = (StreamConnection) Connector.open(m_connectionDetails, Connector.READ);
                if (m_connection == null) {
                    showAlert("connection is null");
                    return;
                }

                m_dataInputStream = m_connection.openDataInputStream();
                if (m_dataInputStream == null) {
                    showAlert("InputStream is null");
                    return;
                }
            } catch (IOException ioe) {
                showAlert("problem: Exception: Unable to open conn/streams");
                ioe.printStackTrace();

                return;
            }

            try {
                // receiving data
                byte[] rb = new byte[512];
                int length = m_dataInputStream.read(rb);

                System.out.println("BYTES RECEIVED " + length + " AND " + new String(rb, 0, length));

                showAlert(new String(rb, 0, length));

            } catch (Exception e) {
                showAlert("problem:" + e.getMessage());
                e.printStackTrace();

            } finally {
                try {
                    // releasing resources that were allocated
                    if (m_dataInputStream != null) {
                        m_dataInputStream.close();
                    }
                    if (m_connection != null) {
                        m_connection.close();
                    }
                } catch (IOException ioe) {
                    System.out.println("Could not free the resources");
                    ioe.printStackTrace();
                }
            }
        }
    }

    private Reader m_reader;

    private Display m_display;
    private Form m_mainForm;
    private TextField m_urlTextBox;
    //private StringItem m_MsgItem;

    private Command m_exitCommand;
    private Command m_getCommand;


    public BasicSocketMIDlet() {

        //TODO: Does not work yet?
        String connectionDetails = getAppProperty("default-connection");
        System.out.println(connectionDetails);

        if (connectionDetails != null) {
            m_connectionDetails = "socket://" + connectionDetails;
        }

        m_mainForm = new Form("Exchanging Msgs");

        // create the backCommand, okCommand and the exitCommand
        m_exitCommand = new Command("Exit", Command.EXIT, 1);
        m_mainForm.addCommand(m_exitCommand);

        m_getCommand = new Command("Start", Command.SCREEN, 1);
        m_mainForm.addCommand(m_getCommand);

        m_urlTextBox = new TextField("Enter server url", m_connectionDetails, 50, TextField.ANY);
        m_mainForm.append(m_urlTextBox);


        // instantiating the listener
        m_mainForm.setCommandListener(new CommandListener() {

            public void commandAction(Command c, Displayable d) {
                if (c == m_exitCommand) {
                    exit();
                } else if (c == m_getCommand) {
                    //m_ConnectionDetails = m_URLTextBox.getString();

                   Thread thread = new Thread(getReader());
                   thread.start();
                }
            }

            public void exit() {
                destroyApp(true);
                notifyDestroyed();
            }
        });

        // getting the display object
        m_display = Display.getDisplay(this);
    }

    public void startApp() {
        m_display.setCurrent(m_mainForm);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean cond) {
        m_display = null;
        m_mainForm = null;
        m_exitCommand = null;
        m_getCommand = null;
    }



    private void showAlert(String msg) {
        Alert alert = new Alert(msg);
        alert.setTimeout(Alert.FOREVER);

        m_display.setCurrent(alert);
    }

    private Runnable getReader() {
        if (m_reader == null) {
            m_reader = new Reader();
        }
        return m_reader;
    }
 }
